<?php
/**
 *
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/5/28 14:36
 * @copyright PanxSoft Inc.
 */

namespace App\Http\Controllers\Admin\V1;


use App\Http\Controllers\ApiController;
use App\Http\Requests\Admin\V1\AdminLogin\AdminLoginRequest;
use App\Models\Admin;
use App\Services\Utils\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\JWTAuth;
use Tymon\JWTAuth\JWTGuard;

class AdminLoginController extends ApiController
{
    const ROUTES = [
        'login'      => 'admin.v1.admin-login.login',
    ];

    /**
     * 后端管理员登录
     *
     * @param AdminLoginRequest $request
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function login(AdminLoginRequest $request)
    {
        $account = $request->get('account');

        $admin = $this->checkGetAdmin($account, $request->get('password'));

        $token = Guard::JWTAdminLogin($admin);

        return $this->response(compact('admin', 'token'));
    }

    /**
     * @param $account
     * @param $password
     *
     * @return Admin
     * @throws \App\Exceptions\ApiAbstractException
     */
    private function checkGetAdmin(string $account,
                                   string $password): Admin
    {
        $admin = (new Admin)->where(compact('account'))->first();
            $this->checkItemExist($admin, trans('checker.app.login.phone'));
            $this->checkIsTrue(password_verify($password, $admin->password), trans('checker.password_verify_error'));

        return $admin;
    }

    /**
     * @param $admin
     *
     * @return string
     */
    private function JWTLogin(Admin $admin): string
    {
        /** @var JWTAuth|JWTGuard $guard */
        $guard = Auth::guard(Admin::GUARD_NAME);

        $token = $guard->login($admin);

        return $token;
    }
}